/*
** StockDB
**
** Copyright (C) 2012 - ? doublegsoft
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "request.h"

#include <stddef.h>
#include <stdlib.h>
#include <string.h>

/*!
** pointer to reqbuf_t link list head
*/
reqbuf_t *head = NULL;

/*!
** pointer to reqbuf_t link list tail
*/
reqbuf_t *tail = NULL;

reqbuf_t *
stockdb_create_reqbuf(int remote)
{
  reqbuf_t *ret = (reqbuf_t *)malloc(sizeof(reqbuf_t));
  ret->remote = remote;
  ret->length = 0;
  ret->data = NULL;
  ret->next = NULL;
  return ret;
}

reqbuf_t *
stockdb_find_reqbuf(int remote)
{
  reqbuf_t *tmp = head;
  if (! tmp)
  {
    tmp = stockdb_create_reqbuf(remote);
    head = tmp;
    tail = tmp;
    return tmp;
  }
  while (tmp)
  {
    if (tmp->remote == remote)
    {
      return tmp;
    }
    else
    {
      tmp = tmp->next;
    }
  }
  tmp = stockdb_create_reqbuf(remote);
  tail->next = tmp;
  tail = tmp;
  return tmp;
}

void
stockdb_delete_reqbuf(int remote)
{
  reqbuf_t *prev = head;
  reqbuf_t *tmp = head;
  while (tmp)
  {
    if (tmp->remote == remote)
    {
      if (tmp == head)
      {
        head = NULL;
        tail = NULL;
      }
      prev->next = tmp->next;
      if (tmp->data) free(tmp->data);
      free(tmp);
      tmp = NULL;
      return;
    }
    else
    {
      prev = tmp;
      tmp = tmp->next;
      if (! prev->next)
        tail = prev;
    }
  }
}

void
stockdb_append_data(reqbuf_t *req, char *buf, int size)
{
  if (req->data)
  {
    char *tmp = req->data;
    req->data = malloc(req->length + size);
    char *p = req->data + req->length;
    memcpy(req->data, tmp, req->length);
    req->length += size;
    memcpy(p, buf, size);
    free(tmp);
  }
  else
  {
    req->data = malloc(size);
    req->length = size;
    memcpy(req->data, buf, size);
  }
}


